<template>
	<el-checkbox-group v-model="retuenValue" @change="onChange">
		<el-checkbox v-for="(item, index) in optionsList" :key="item[valueKey]" :label="item[valueKey]">
			<slot v-bind="item" :$index="index">{{ item[labelKey] }}</slot>
		</el-checkbox>
	</el-checkbox-group>
</template>

<script setup>
import { computed, ref, watch } from "vue"
import { useDictStore } from "/store/dict"

const props = defineProps({
	modelValue: {
		type: [String, Number, Array],
		default: "",
	},
	dict: {
		type: [String, Array],
		default: "",
	},
	label: {
		type: String,
		default: "",
	},
	value: {
		type: String,
		default: "",
	},
	disabled: {
		type: Boolean,
		default: false,
	},
	spacer: {
		type: String,
		default: ",",
	},
	join: {
		type: String,
	},
})
const emits = defineEmits(["update:modelValue", "change"])
const retuenValue = computed({
	get() {
		if (props.modelValue === null || props.modelValue === "") {
			return []
		}
		if (Array.isArray(props.modelValue)) {
			return props.modelValue.map(item => item + "")
		} else {
			return (props.modelValue + "").split(props.spacer)
		}
	},
	set(value) {
		if (Array.isArray(value)) {
			if (props.join || props.spacer) {
				emits("update:modelValue", value.join(props.join || props.spacer))
			} else {
				emits("update:modelValue", value)
			}
		} else {
			emits("update:modelValue", [value])
		}
	},
})
const labelKey = computed(() => {
	if (props.label) {
		return props.label
	}
	return "name"
})
const valueKey = computed(() => {
	if (props.value) {
		return props.value
	}
	return "code"
})
const optionsList = ref([])
function refreshOptionsList() {
	if (typeof props.dict === "string") {
		const dictStore = useDictStore()
		dictStore.getDict(props.dict).then(resule => {
			optionsList.value = resule.map(item => ({ ...item, [valueKey.value]: item[valueKey.value] + "" }))
		})
		return
	}
	optionsList.value = props.dict.map(item => ({ ...item, [valueKey.value]: item[valueKey.value] + "" }))
}
refreshOptionsList()
watch(
	() => props.dict,
	() => {
		if (!props.dict) {
			return
		}
		refreshOptionsList()
	},
	{
		deep: true,
	}
)

function onChange(value) {
	emits("change", value)
}
</script>

<script>
export default {
	name: "v-checkbox",
}
</script>

<style lang="scss" scoped></style>
